<template>
  <el-row>
    <el-form :model="searchForm" ref="queryForm" :inline="true" size="default">
      <el-form-item label="" prop="value">
        <el-input v-model="searchForm.value" placeholder="请输入客户信息" class="input-with-select">
          <template #prepend>
            <el-select v-model="searchForm.select" placeholder="请选择条件" style="width: 115px">
              <el-option label="客户姓名" value="1" />
              <el-option label="客户房间" value="2" />
            </el-select>
          </template>
          <template #append>
            <el-button icon="Search" @click="handleSearch" />
          </template>
        </el-input>
      </el-form-item>
    </el-form>

    <el-col :span="1.5" class="divider">
      <div v-hasPerms="'butler.outward.inisert'">
        <el-button class="insertButton" type="primary" icon="Plus" size="default"
                   @click="insertEdit">外出申请</el-button>
      </div>
    </el-col>
  </el-row>

  <!-- 分割线 -->
  <div>
    <el-divider>
      <el-icon>
        <OfficeBuilding />
      </el-icon>
    </el-divider>
  </div>

  <div class="common-layout">
    <el-container>
      <el-aside class="customerInfo">
        <div class="title">
          <h2>客户信息</h2>
        </div>
        <el-row v-loading="loading">
          <el-table :data="tableData" size="large" @row-click="handleCustomerRowClick"
                    style="cursor: pointer">
            <el-table-column prop="indexId" label="序号" type="index" width="60" align="center" />
            <el-table-column prop="customerName" label="客户姓名" width="90x" align="center" />
            <el-table-column prop="customerAge" label="客户年龄" width="70px" align="center" />
            <el-table-column prop="customerSex" label="客户性别" width="70px" align="center" />
            <el-table-column prop="roomNo" label="房间号" width="85px" align="center" />
            <el-table-column prop="bedId" label="床位号" width="85px" align="center" />
            <el-table-column prop="levelId" label="护理级别" width="70px" align="center" />
          </el-table>
          <el-pagination style="margin: 20px 40px;" layout="prev, pager, next, jumper, ->, total,"
                         :total="customerParams.total" v-model:page-size="customerParams.size"
                         v-model:current-page="customerParams.current" @current-change="customerList"
                         @size-change="customerList" />
        </el-row>
      </el-aside>

      <el-aside class="outward">
        <div class="title">
          <h2>外出登记</h2>
        </div>
        <el-row v-loading="loading">
          <el-table :data="outwardData" size="large">
            <el-table-column prop="indexId" label="序号" type="index" width="60" align="center"
                             fixed="left" />
            <el-table-column prop="customerName" label="客户姓名" width="90x" align="center" fixed="left" />
            <el-table-column prop="outgoingreason" label="外出事由" width="100px" align="center" />
            <el-table-column prop="outgoingtime" label="外出时间" width="110px" align="center" />
            <el-table-column prop="expectedreturntime" label="预计回院时间" width="120px" align="center" />
            <el-table-column prop="actualreturntime" label="实际回院时间" width="120px" align="center" />
            <el-table-column prop="escorted" label="陪同人姓名" width="75px" align="center" />
            <el-table-column prop="relation" label="陪同人关系" width="75px" align="center" />
            <el-table-column prop="escortedtel" label="陪同人电话" width="120px" align="center" />
            <el-table-column prop="auditstatus" label="审批状态" width="90px" align="center">
              <template #default="scope">
                                <span v-if="scope.row.auditstatus === 0">
                                    <el-tooltip content="请等待审批" placement="top">
                                        <el-button type="info">待审批</el-button>
                                    </el-tooltip>
                                </span>
                <span v-else-if="scope.row.auditstatus === 1">
                                    <el-tooltip content="注意安全，请按时归队" placement="top">
                                        <el-button type="success">已同意</el-button>
                                    </el-tooltip>
                                </span>
                <span v-else-if="scope.row.auditstatus === 2">
                                    <el-tooltip content="已拒绝" placement="top">
                                        <el-button type="danger">已拒绝</el-button>
                                    </el-tooltip>
                                </span>
                <span v-else>未知状态</span>
              </template>
            </el-table-column>

            <el-table-column fixed="right" label="操作" align="center" min-width="180px">
              <template #default="scope">
                <!--
                    外面还应该加一层 判断是否为管理员
                    管理员 可设置同意拒绝 登记回院时间
                    管家   可设置修改删除 登记回院时间
                -->
                <!-- 当审批状态为0时，显示同意和拒绝按钮 -->
                <div v-if="scope.row.auditstatus === 0" v-hasPerms="'admin.outward.agreeAndRefuse'">
                  <el-button type="success" size="small" icon="Select" round
                             @click="agreeOutward(scope.row, 1)">同意
                  </el-button>
                  <el-button type="danger" size="small" icon="Close" round
                             @click="agreeOutward(scope.row, 2)">拒绝
                  </el-button>
                </div>
                <div v-if="scope.row.auditstatus === 0" v-hasPerms="'butler.outward.updateAndDelete'">
                  <el-button type="primary" size="small" icon="Edit" round
                             @click="updateEdit(scope.row.outwardId)">修改
                  </el-button>
                  <el-button type="danger" size="small" icon="Delete" round
                             @click="deleteOutward(scope.row.outwardId)">撤回
                  </el-button>
                </div>
                <!-- 当审批状态为1时，显示登记会员时间按钮 -->
                <div v-if="scope.row.auditstatus === 1" v-hasPerms="'butler.outward.return'">
                  <div v-if="scope.row.actualreturntime === null">
                    <el-button type="success" size="small" icon="Check" plain
                               @click="customerRetrunTime(scope.row)">回院登记</el-button>
                  </div>
                  <div v-else>
                    <el-button type="success" size="small" icon="Check" plain
                               disabled>回院登记</el-button>
                  </div>
                </div>
                <!-- 当审批状态为2时，显示拒绝申请按钮 -->
                <div v-if="scope.row.auditstatus === 2">
                  <el-button type="danger" size="small" icon="Close" round disabled>拒绝申请</el-button>
                </div>
              </template>
            </el-table-column>

          </el-table>
          <el-pagination style="margin: 20px 40px;" layout="prev, pager, next, jumper, ->, total,"
                         :total="outwardParams.total" v-model:page-size="outwardParams.size"
                         v-model:current-page="outwardParams.current" @current-change="queryList"
                         @size-change="queryList" />
        </el-row>

        <el-dialog v-model="showEdit" title="客户信息" style="width: 400px;">
          <EditView v-if="showEdit" :closeEdit="closeEdit" :editId="editId" />
        </el-dialog>
      </el-aside>
    </el-container>


    <el-dialog title="登记回院时间" v-model="showReturnTimeDialog" style="width: 400px;">
      <el-form label-width="auto" class="form-container">
        <el-form-item label="预计回院时间">
          <div class="block">
            <el-date-picker v-model="returnForm.actualreturntime" type="datetime" placeholder="请登记回院时间"
                            :size="size" style="width: 200px" value-format="YYYY-MM-DD HH:mm:ss"
                            format="YYYY-MM-DD HH:mm:ss" />
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="sureReturnTime">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup name="checkIn">
import { onMounted } from 'vue'
import { ref } from 'vue'
import EditView from './edit.vue'
import { CustomerInfo, listInfo, removeById, selectListWithCustomerName, updateAuditStatus, actualReturnTime } from '@/api/customer/outward/index.js'
import { ElMessageBox, ElNotification } from 'element-plus'
import { reactive } from 'vue'

// 搜索表单
const searchForm = ref({
  select: '1', // 默认选择客户姓名
  value: ''
})

// 定义加载状态
const loading = ref(true)

// 表格数据
const tableData = ref([])
const outwardData = ref([])

// ***** 多条件查询
// 查询条件 - 分开管理两个表格的查询参数
const customerParams = ref({
  customerName: '',
  roomNo: '',
  current: 1,
  size: 10,
  total: 0
})

// 外出表格查询参数
const outwardParams = ref({
  customerName: '',
  roomNo: '',
  current: 1,
  size: 10,
  total: 0
})


const showReturnTimeDialog = ref(false)
const returnForm = reactive({
  outwardId: null,
  actualreturntime: ''
})
// 处理搜索
function handleSearch() {
  // 重置两个表格的页码
  customerParams.value.current = 1
  outwardParams.value.current = 1

  // 根据搜索条件设置查询参数
  if (searchForm.value.select === '1') {
    // 根据客户姓名查询
    customerParams.value.customerName = searchForm.value.value;
    customerParams.value.roomNo = '';
    outwardParams.value.customerName = searchForm.value.value;
    outwardParams.value.roomNo = '';
  } else if (searchForm.value.select === '2') {
    // 根据房间号查询
    customerParams.value.customerName = '';
    customerParams.value.roomNo = searchForm.value.value;
    outwardParams.value.customerName = '';
    outwardParams.value.roomNo = searchForm.value.value;
  }

  // 执行查询
  customerList()
  queryList()
}
// *****

// 客户信息查询（左侧）
async function customerList() {
  loading.value = true
  try {
    const page = await CustomerInfo(customerParams.value)

    // console.log("customerParams" + customerParams.value);
    // console.log("page" + page);

    tableData.value = page.records
    customerParams.value.total = page.total
  } catch (e) {
    console.error('客户信息查询失败:', e)
  } finally {
    loading.value = false
  }
}

// 外出登记查询（右侧）
async function queryList() {
  loading.value = true
  try {
    const page = await selectListWithCustomerName(outwardParams.value)

    // console.log("outwardParams" + outwardParams.value);
    // console.log("page" + page);

    outwardData.value = page.records
    outwardParams.value.total = page.total
  } catch (e) {
    console.error('外出登记查询失败:', e)
  } finally {
    loading.value = false
  }
}

// 处理客户行点击事件 （点击客户信息显示外出登记）
const handleCustomerRowClick = (row) => {
  // 设置查询参数为当前点击的客户姓名
  outwardParams.value.customerName = row.customerName;
  outwardParams.value.roomNo = '';

  // 重置页码
  outwardParams.value.current = 1;

  // 执行查询
  queryList();

  // 同时更新搜索框的值，保持一致性
  searchForm.value.select = '1';
  searchForm.value.value = row.customerName;
}

// *****外出审批******
// 同意或者拒绝
const agreeOutward = async (row, status) => {
  try {
    // 更新状态为1（同意）
    const outwardId = row.outwardId;
    // 修改的方法
    await updateAuditStatus(outwardId, status);
    if (status == 1) {
      ElNotification({
        title: '消息',
        type: 'success',
        message: "已同意"
      });
    }
    if (status == 2) {
      ElNotification({
        title: '消息',
        type: 'success',
        message: "已拒绝"
      });
    }
    // 刷新表格数据
    queryList();
  } catch (e) {
    console.error('审批失败:', e);
    ElNotification({
      title: '错误',
      type: 'error',
      message: "审批失败"
    });
  }
};

// 回院登记
const customerRetrunTime = async (row) => {
  // 弹出时间选择对话框
  showReturnTimeDialog.value = true;

  // // 获取登记的用户编号
  returnForm.outwardId = row.outwardId;
};

// 回院时间登记
const sureReturnTime = async () => {
  try {
    // 调用实际返回时间登记函数
    const success = await actualReturnTime(returnForm);

    // 判断操作是否成功
    if (success) {
      // 成功通知
      ElNotification({
        title: '消息',
        type: 'success',
        message: "已登记"
      });
    } else {
      // 失败通知
      ElNotification({
        title: '错误',
        type: 'error',
        message: "登记失败"
      });
    }
    // 重新查询列表更新数据
    customerList()
    queryList()
    // 登记完成后关闭对话框
    showReturnTimeDialog.value = false;
  } catch (error) {
    // 异常处理，显示错误通知
    console.error('返回时间提交时出错s:', error);
    ElNotification({
      title: '错误',
      type: 'error',
      message: "登记处理失败"
    });
    sureReturnTime(false);
    // 查询列表更新数据
    queryList();
  }

}


// 是否展示修改的表单
const showEdit = ref(false)
const editId = ref(0)

// 关闭添加子组件页面
const closeEdit = (query) => {
  showEdit.value = false
  if (query) {
    customerList()
    queryList()
  }
}

// 新增按钮
const insertEdit = () => {
  editId.value = 0
  showEdit.value = true
}

// 修改按钮
const updateEdit = (outwardId) => {
  editId.value = outwardId
  showEdit.value = true

  console.log("editId");
  console.log(editId.value);
}

// 撤销申请按钮
const deleteOutward = (id) => {
  // console.log("row:",id);
  ElMessageBox.confirm(
      '是否确认删除该用户信息?',
      'Warning',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    removeById(id).then(_success => {
      ElNotification({
        title: '消息',
        type: 'success',
        message: "删除成功",
      })
      customerList()
      queryList()
    })
  })
}

// 加载当前页面完成之后查询
onMounted(() => {
  customerList()
  queryList()
})
</script>

<style scoped>
.input-with-select .el-input-group__prepend {
  background-color: var(--el-fill-color-blank);
}

.insertButton {
  margin: 0px 0px 10px 0px;
}

.divider {
  margin: 0px 0px 10px 0px;
}

/* 客户信息 */
.customerInfo {
  width: 550px;
  height: 650px;
  border: 1px solid rgb(0, 0, 0);
  margin-right: 20px;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.customerInfo .title {
  background-color: #61b3ff;
  font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
  text-align: center;
  margin: 0;
  padding: 10px;
  color: #333;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 外出登记 */
.outward {
  margin: 0;
  width: 860px;
  height: 650px;
  border: 1px solid rgb(0, 0, 0);
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.outward .title {
  background-color: #61b3ff;
  font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
  text-align: center;
  margin: 0;
  padding: 10px;
  color: #333;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 添加行悬停效果 */
.el-table__row:hover {
  background-color: #f6f5fa;
}
</style>
